local skynet = require "skynet"
local redis = require "skynet.db.redis"

local db

local conf = {
	host = "127.0.0.1" ,
	port = 6379 ,
	db = 0
}

local function create_redis_connect() 
    return redis.connect(conf)
end 

local function release_redis_connect()
    if db then 
        db:disconnect()
    end 
end 

local function init_redis()
    if db then 

    end 
end 

local CMD = {} 

-- 注册
function CMD.signup(fd, JS_user_info)
    local user_info = cjson.decode(JS_user_info)
    local username, password = user_info.username, user_info.password
    if not db:sismember("user_info", username) then 
        db:sadd("user_info", username)
        db:set(username, JS_user_info)
        return { result = "OK" }
    end 
    -- 有人用了这个ID（username）
    return { result = "NO" }
end 

-- 登入
function CMD.signin(fd, JS_user_info)
    local user_info = cjson.decode(JS_user_info)
    local username, password = user_info.username, user_info.password
    
    -- 用户不在线
    if not db:sismember("logined",  username) then
        local JS_user_info_s = db:get(username)
        
        local user_info_s = cjson.decode(JS_user_info_s)
        local username_s, password_s = user_info_s.username, user_info_s.password

        if username_s == username and password_s == password then 
            db:sadd("logined", username)
            return { result = "OK" }
        end 
        return { result = "NO" }
    end
    -- 用户在线
    return { result = "OK" }
end

-- 用户下线
function CMD.kick(username)
    if db:sismember("logined",  username) then
        db:srem("logined", username)
        db:del(username)
    end
end

skynet.register(...)

skynet.start(function()
    db = create_redis_connect()
    if not db then 
        skynet.error("redis connect failed")
    end 
    init_redis()

    skynet.dispatch("lua", function(session, source, command, ...)
        local f = assert(CMD[string.lower(command)])
        skynet.ret(skynet.pack(f(...)))
    end)
end)
